<!--页面组件-->
<template>
  <div>
    <CCard class="cdHead addTask">
      <div style="display: flex">
        <CCol sm="12" class="showContentRight">
          <CSelect
            label="任务类型"
            @change="pushTaskTypeChange($event)"
            :value.sync="pushTaskType"
            horizontal
            :options="taskTypeList"
            placeholder="请选择"
            class="input"
          />
          <CInput
            label="任务名称"
            v-model="addData.taskName"
            placeholder="请输入任务名称"
            horizontal
            class="input"
          />
          <CSelect
            label="扫描间隔"
            horizontal
            :value.sync="addData.crontabExpress"
            :options="cronList"
            placeholder="请选择"
            class="input"
          />
          <div style="display: flex">
            <CInput
              label="扫描目录"
              v-model="addDataTaskParam.scanDir"
              placeholder="请输入扫描目录"
              horizontal
              class="input"
            />
            <CButton
              color="info"
              size="sm"
              @click="selectPushTaskScanDir('scanDir')"
              class="btnSelect system-btn-style"
              >...</CButton
            >
          </div>
          <div style="display: flex">
            <CInput
              label="生产目录"
              v-model="addDataTaskParam.proDir"
              placeholder="请输入生产目录"
              horizontal
              class="input"
            />
            <CButton
              color="info"
              size="sm"
              @click="selectPushTaskProDir('proDir')"
              class="btnSelect system-btn-style"
              >...</CButton
            >
          </div>
         <!--  <CSelect
            label="组织机构"
            horizontal
            :value.sync="addDataTaskParam.enterId"
            :options="enterpriseList"
            placeholder="请选择"
            @change="selectEnterprise($event)"
            class="input"
          />
           <CSelect
            label="用户部门"
            horizontal
            :value.sync="addDataTaskParam.orgId"
            :options="organizationList"
            placeholder="请选择"
            @change="selectOrganization($event)"
            class="input"
          />
          <CSelect
            label="用户名"
            horizontal
            :value.sync="addDataTaskParam.userId"
            :options="userNameList"
            placeholder="请选择"
            @change="selectUserName($event)"
            class="input"
          />

           <CSelect
            label="文件类型"
            horizontal
            :options="fileTypeList"
            :value.sync="addDataTaskParam.finishFlag"
            placeholder="请选择文件类型"
            @change="selectFileType($event)"
            class="input"
          /> -->
          <CInput
            label="用户部门"
            v-model="addDataTaskParam.department"
            placeholder="请输入用户部门"
            horizontal
            class="input"
          />
          <CInput
            label="用户名"
            v-model="addDataTaskParam.taskOwner"
            placeholder="请输入用户名"
            horizontal
            class="input"
          />
          <CInput
            label="匹配后缀"
            v-model="addDataTaskParam.finishFlag"
            placeholder="后缀必须包含点（例如：.tif）"
            horizontal
            class="input"
          />

          <label class="label" style="padding-right: 15px">流程</label>
          <Select
            filterable
            transfer
            @on-select="processingOnChange"
            style="width: 61%; margin-left: -25px"
          >
            <Option
              v-for="item in processingList"
              :value="item.id"
              :key="item.id"
              >{{
                item.workflowName + "-" + item.workflowVersion + ".0"
              }}</Option
            >
          </Select>


          <div class="select-rou" style="margin-top: 3px;display: flex">
            <label class="label" style="margin-right: 7px;padding-top: 7px" >规则</label>
            <div style="display: flex">
              <Select
                      filterable
                      transfer
                      v-model="addDataTaskParam.selectData"
                      style="width: 71px;height: 35px;"
              >
                <Option
                        v-for="item in selectRow"
                        :value="item.value"
                        :key="item.value">{{item.label }}</Option>
              </Select>

              <CInput
                      v-model="addDataTaskParam.regexExpressData"
                      horizontal
                      style="width: 211px;margin-right: 4px"
                      :placeholder="addDataTaskParam.selectData=='ABC'?'以^开头,以$结尾':'请输入内容'"
                      class="input"
              />
            </div>
          </div>




        </CCol>

        <CCol md="12" class="showContentRight">
          <CForm>
            <ul>
              <li v-for="(item, index) in showParamList" :key="index">
                <CSelect
                  :label="item.dictName"
                  horizontal
                  :options="flowParamList"
                  :value.sync="item.bindingFlowKey"
                  placeholder="请选择"
                ></CSelect>
              </li>
            </ul>
          </CForm>
        </CCol>
      </div>
    </CCard>

    <Modal
      v-model="showPushTaskZtreeModal"
      draggable
      scrollable
      title="推送任务选择目录"
      id="my-modal"
    >
      <!-- :styles="modalStyle" -->
      <p slot="header" class="modalHeader">选择目录</p>
      <CButtonClose slot="close" @click="pushTaskMenuCancel" />
      <div class="treeDiv">
        <ul id="pushTaskTree" class="ztree"></ul>
      </div>

      <template #footer>
        <CButton @click="pushTaskMenuCancel" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="pushTaskMenuOk" color="info" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </Modal>

    <!-- <CModal
      title="推送任务选择目录"
      color="info"
      :show.sync="showPushTaskZtreeModal"
      :closeOnBackdrop="false"
      size="lg"
      centered
    >
      <div class="treeDiv">
        <ul id="pushTaskTree" class="ztree"></ul>
      </div>

      <template #header>
        <h5>选择目录</h5>
        <CButtonClose @click="pushTaskMenuCancel" />
      </template>
      <template #footer>
        <CButton @click="pushTaskMenuOk" color="info">确定</CButton>
        <CButton @click="pushTaskMenuCancel" color="light">取消</CButton>
      </template>
    </CModal> -->
  </div>
</template>
<script>
export default {
  name: "addTask",

  data() {
    return {
      // modalStyle: { top: "250px" },
      flowkeyList: {},
      showParamList: [],
      flowParamList: [],

      selectRow: [
        {label:"文件开头",value:"^ABC.*$"},
        {label:"文件结尾",value:"^.*ABC$"},
        {label:"文件包含",value:"^.*ABC.*$"},
        {label:"文件不包含",value:"^((?!ABC).)*$"},

    /*    {label:"不包含ABC",value:"^((?!ABC).)*str((?!ABC).)*$"},*/
         {label:"自定义",value:"ABC"},
      ],

      processingList: [],
      sourceId: 2,
      cronList: [],
      pushTaskType: 2, //2常规任务 1是应急任务
      bIsScanDir: true,
      taskTypeList: [
        // {
        //   value: "EmergencyTask",
        //   label: "应急任务",
        // },
        // {
        //   value: "RoutineTask",
        //   label: "常规任务",
        // },
      ],
      items: [],

      addData: {
        flowName: "",
        crontabExpress: "",
        flowId: "",
        sourceId: 2,
        taskName: "",
        taskParameter: "",
      },
      addDataTaskParam: {
        selectData: "",
        regexExpressData: "",
        regexExpress: "",
        scanDir: "",
        proDir: "",
        finishFlag: "",
        taskOwner: "", //任务发起者 用户
        department: "", //发起者部门
        // enterId: -1, //组织机构
        // orgId: -1, //部门
        // userId: -1, //用户
      },



      // fileTypeList: [".gz", ".zip"],
      enterpriseList: [],
      organizationList: [],
      userNameList: [],
      showPushTaskZtreeModal: false,
      haveHeader: false,
    };
  },
  computed: {
    getRegexExpress() {

      return "";
    }



  },
  mounted() {
    // this.source();
    this.getCronList();
    // this.getEnterpriseList();
  },
  methods: {
    init() {
      this.getTaskTypeByDictCode();
      this.getParamByDictCode(); //右侧字典列表
      this.getProcessingData(); //流程下拉参数
    },
    getParamByDictCode() {
      let path = this.$api.processingApi.getAllChildByDictCode;
      let param = {
        dictCode: "flowKey",
      };
      this.http.get(path, param).then((res) => {
        if (res.data.code == 0 && res.data.success) {
          this.showParamList = res.data.data.dictCodeList;
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    getTaskTypeByDictCode() {
      let path = this.$api.processingApi.getAllChildByDictCode;
      let param = {
        dictCode: "timingTask",
      };
      this.http.get(path, param).then((res) => {
        if (res.data.code == 0 && res.data.success) {
          let dictCodeList = res.data.data.dictCodeList;
          for (let dictCode of dictCodeList) {
            let obj = {
              label: dictCode.dictName,
              value: parseInt(dictCode.dictCode),
            };
            this.taskTypeList.push(obj);
          }
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    getProcessingData() {
      let path = this.$api.processingApi.search;
      this.http.get(path).then((res) => {
        if (res.data.code == 0) {
          this.processingList = res.data.data;
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    processingOnChange(item) {
      this.addData.flowId = item.value;
      // let index = item.label.lastIndexOf("-");
      // this.addData.flowName = item.label.substring(
      //   0,
      //   item.label.length - index
      // );
      this.addData.flowName = item.label;
      this.getflowParamsByFlowId(item.value);
    },
    getflowParamsByFlowId(flowId) {
      let path = this.$api.processingApi.getParam;
      let param = {
        workFlowId: flowId,
      };
      this.flowParamList = [];
      this.http.get(path, param).then((res) => {
        if (res.data.code == 0) {
          let globalParam = JSON.parse(res.data.data.processParameters)
            .globalParam;
          let inputParam = JSON.parse(res.data.data.processParameters)
            .inputParam;

          for (let gParam of globalParam) {
            let label = "基本参数" + " - " + gParam.label;
            let globalFlowParam = {
              label: label,
              value: gParam.workflowInputKey,
            };
            this.flowParamList.push(globalFlowParam);
          }

          for (let paramFlow of inputParam) {
            for (let paramAlgo of paramFlow) {
              let label = paramAlgo.groupName + " - " + paramAlgo.label;
              let flowParam = {
                label: label,
                value: paramAlgo.workflowInputKey,
              };
              this.flowParamList.push(flowParam);
            }
          }
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    selectFileType(event) {
      this.addDataTaskParam.finishFlag = event.target.value;
    },
    source() {
      let self = this;
      let path = this.$api.processingApi.source;
      this.http.get(path).then((res) => {
        if (res.data.code == 0) {
          self.addData.sourceId = res.data.data[0].id;
        } else {
          console.log("查询sourceid错误");
        }
      });
    },

    // 任务类型选择变化
    pushTaskTypeChange(event) {
      this.pushTaskType = parseInt(event.target.value);

      this.addData.sourceId = this.pushTaskType;
    },
    // 应急推送任务扫描目录选择
    selectPushTaskScanDir(type) {
      this.bIsScanDir = true;
      this.showPushTaskZtreeModal = true;
      this.pushTaskMenu(type);
    },
    // 应急推送任务生产目录选择
    selectPushTaskProDir(type) {
      this.bIsScanDir = false;
      this.showPushTaskZtreeModal = true;
      this.pushTaskMenu(type);
    },
    // 应急推送任务扫描目录、生产目录Ztree设置
    pushTaskMenuSetting(urlPath) {
      let checkType = { Y: "", N: "" }; //父与子的关联去掉
      let setting = {
        check: {
          enable: true,
          nocheckInherit: false,
          chkboxType: checkType,
        },
        data: {
          simpleData: {
            enable: true,
          },
        },
        callback: {
          beforeClick: this.beforeClick,
          onClick: this.zTreeOnClick,
          onCheck: this.zTreePushTaskOnCheck,
          onExpand: this.zTreeOnClick,
        },
      };

      this.http.get(urlPath).then((res) => {
        let data = res.data;
        if (data.success == true) {
          $.fn.zTree.init($("#pushTaskTree"), setting, data.data);
        }
      });
    },
    pushTaskMenu(type) {
      let treeObj = $.fn.zTree.getZTreeObj("pushTaskTree");
      if (treeObj != null) {
        var nodes = treeObj.getNodes();
        for (var i = nodes.length - 1; i >= 0; i--) {
          treeObj.removeNode(nodes[i]);
        }
      }

      let path; //1为共享文件夹,2为用户文件夹,3为紧急推送扫描文件夹,4为应急任务生产根目录,5为常规推送生产根目录,6为自动推送Modis生产根目录,7为自动推送Modis扫描根目录
      if (type == "scanDir") {
        if (this.pushTaskType == 1) {
          path = this.$api.processingApi.fileRootPath + 3;
        } else if (this.pushTaskType == 2) {
          path = this.$api.processingApi.fileRootPath + 5; //1;
        } else if (this.pushTaskType === "ModisTask") {
          path = this.$api.processingApi.fileRootPath + 7;
        } else {
          path = this.$api.processingApi.fileRootPath + 1;
        }
      } else {
        if (this.pushTaskType == 1) {
          path = this.$api.processingApi.fileRootPath + 4;
        } else if (this.pushTaskType == 2) {
          path = this.$api.processingApi.fileRootPath + 5;
        } else if (this.pushTaskType === "ModisTask") {
          path = this.$api.processingApi.fileRootPath + 6;
        } else {
          path = this.$api.processingApi.fileRootPath + 1;
        }
      }
      this.pushTaskMenuSetting(path);
    },
    zTreePushTaskOnCheck(event, treeId, treeNode) {
      var treeObj = $.fn.zTree.getZTreeObj(treeId),
        nodes = treeObj.getCheckedNodes(true);

      if (!treeNode.isParent) {
        this.$Message.warning("请选择文件夹！");
        treeNode.checked = false;
        treeObj.updateNode(treeNode);
        return;
      }
      if (!this.bIsScanDir && nodes.length > 1) {
        //限制单个文件夹
        this.$Message.warning("生产目录只能选择一个文件夹！");
        treeNode.checked = false;
        treeObj.updateNode(treeNode);
        return;
      }
    },
    pushTaskMenuOk() {
      let treeObj = $.fn.zTree.getZTreeObj("pushTaskTree"),
        nodes = treeObj.getCheckedNodes(true);
      let tempNode = "";
      let info = "";
      for (var index in nodes) {
        tempNode = nodes[index];
        if (info == "") {
          info = tempNode.id;
        } else {
          info += ";" + tempNode.id;
        }
      }

      if (this.bIsScanDir) {
        this.addDataTaskParam.scanDir = info;
      } else {
        this.addDataTaskParam.proDir = info;
      }

      this.pushTaskReset();
    },
    pushTaskMenuCancel() {
      this.pushTaskReset();
    },
    pushTaskReset() {
      var treeObj;
      this.showPushTaskZtreeModal = false;
      treeObj = $.fn.zTree.getZTreeObj("pushTaskTree");
      if (treeObj == null) return;

      var nodes = treeObj.getNodes();
      for (var i = nodes.length - 1; i >= 0; i--) {
        treeObj.removeNode(nodes[i]);
      }
    },

    zTreeOnClick(event, treeId, treeNode) {
      let path = this.$api.processingApi.getFileListByPath;
      let param = {
        path: treeNode.id,
      };
      var treeObj = $.fn.zTree.getZTreeObj(treeId);
      var node = treeObj.getNodeByParam("id", treeNode.id);
      treeObj.selectNode(node);
      let sNode = treeObj.getSelectedNodes();
      if (sNode.length > 0) {
        let zAsync = sNode[0].zAsync;
        treeObj.reAsyncChildNodes(treeNode, "refresh");
        if (zAsync) {
        } else {
          this.http.get(path, param).then((res) => {
            let data = res.data;
            if (data.success == true) {
              treeNode.halfCheck = false;
              treeObj.addNodes(treeNode, data.data, false);
              sNode[0].zAsync = true;
            }
          });
        }
      }
    },

    //被父组件调用
    save() {
      let self = this;
      let path = this.$api.processingApi.create;
      this.getFlowKey();
      //处理匹配后缀的格式是否包含.
      // let suffix = self.addDataTaskParam.finishFlag;
      // if (suffix.indexOf(".") !== 0) {
      //   self.addDataTaskParam.finishFlag = "." + suffix;
      // }

      this.addDataTaskParam.regexExpress =this.addDataTaskParam.regexExpressData? this.addDataTaskParam.selectData.replace("ABC", this.addDataTaskParam.regexExpressData):"";

      self.addData.taskParameter = JSON.stringify(self.addDataTaskParam);
      let param = {
        crontabExpress: self.addData.crontabExpress,
        flowId: self.addData.flowId,
        flowName: self.addData.flowName,
        sourceId: self.addData.sourceId,
        taskName: self.addData.taskName,
        status: 0,
        taskParameter: self.addData.taskParameter,
        flowKey: JSON.stringify(this.flowkeyList),
      };

      this.http.post(path, param).then((res) => {
        if (res.data.success) {
          this.reset();
          this.$Message.success("创建成功");
        } else {
          self.pushTaskType = 2;
          this.$Message.error(res.data.message);
        }
      });
    },
    getFlowKey() {
      this.showParamList.forEach((ele) => {
        this.flowkeyList[ele.dictCode] = ele.bindingFlowKey;
      });
    },
    //取消
    reset() {
      let self = this;
      self.pushTaskType = 2;
      self.resetAddData();
      this.$emit("closeAddTask", false);
    },

    resetAddData() {
      let self = this;
      self.addData.taskName = "";
      self.addData.crontabExpress = "";
      // self.addData.flowId = "";
      // self.addData.flowName = "";
      self.addData.sourceId = 2;
      self.addData.taskParameter = "";

      self.addDataTaskParam.scanDir = "";
      self.addDataTaskParam.proDir = "";
      self.addDataTaskParam.finishFlag = ".gz";
      self.addDataTaskParam.taskOwner = "";
      self.addDataTaskParam.department = "";
      // self.addDataTaskParam.enterId = -1;
      // self.addDataTaskParam.orgId = -1;
      // self.addDataTaskParam.userId = -1;

      self.taskTypeList = [];
    },

    getCronList() {
      let path = this.$api.processingApi.getAllChildByDictCode;
      let param = {
        dictCode: "cron",
      };
      this.http.get(path, param).then((res) => {
        if (res.data.code == 0) {
          let dictCodeList = res.data.data.dictCodeList;
          for (let dictCode of dictCodeList) {
            let cron = {
              label: dictCode.dictName,
              value: dictCode.dictCode,
            };
            this.cronList.push(cron);
          }
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },

    /*

    getEnterpriseList() {
      let self = this;
      self.enterpriseList = [];
      let path = self.$api.processingApi.getTree;
      let param = {
        isTree: false,
      };
      this.http.get(path, param).then((res) => {
        if (res.data.success) {
          let content = res.data.data;
          for (let i = 0; i < content.length; i++) {
            let enterprise = {
              value: content[i].id,
              label: content[i].name,
            };
            self.enterpriseList.push(enterprise);
          }
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    selectEnterprise($event) {
      let self = this;
      self.addDataTaskParam.enterId = parseInt(event.target.value);
      self.getOrganizationList(self.addDataTaskParam.enterId);
    },

    getOrganizationList(enterpriseId) {
      let self = this;
      self.organizationList = [];
      let path = this.$api.processingApi.organization;
      let param = {
        enterId: enterpriseId,
        isTree: false,
      };

      this.http.get(path, param).then((res) => {
        if (res.data.success) {
          let content = res.data.data;

          for (let i = 0; i < content.length; i++) {
            let organization = {
              value: content[i].id,
              label: content[i].name,
            };
            self.organizationList.push(organization);
          }
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    selectOrganization($event) {
      let self = this;

      let selectedIndex = event.target.options.selectedIndex;
      let organizationName = event.target.options[selectedIndex].label;

      self.addDataTaskParam.orgId = parseInt(event.target.value);
      self.addDataTaskParam.department = organizationName;
      self.getUserNameList(self.addDataTaskParam.orgId);
    },
    getUserNameList(organizationId) {
      let self = this;
      self.userNameList = [];
      let path = self.$api.processingApi.queryAllUser;
      let param = {
        Authorization: window.sessionStorage.getItem("PIECloud-Token"),
        organizationId: organizationId,
      };

      this.http.get(path, param).then((res) => {
        if (res.data.success) {
          let content = res.data.data;

          for (let i = 0; i < content.userList.length; i++) {
            let userName = {
              value: content.userList[i].id,
              label: content.userList[i].username,
            };
            self.userNameList.push(userName);
          }
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    selectUserName($event) {
      let self = this;

      let selectedIndex = event.target.options.selectedIndex;
      let userName = event.target.options[selectedIndex].label;

      self.addDataTaskParam.userId = parseInt(event.target.value);
      self.addDataTaskParam.taskOwner = userName;
    },*/
  },
};
</script>
<style scoped>
.label {
  width: 80px;
  margin-right: 20px;
  text-align: right;
}

.input {
  width: 300px;
  cursor: pointer;
}
</style>
<style lang='scss' scoped>
.treeDiv {
  height: 500px;
  // width: 760px;
  width: 504px;
  overflow-y: auto;
}
.btnSelect {
  width: 30px;
  height: 26px;
  margin-left: 10px;
  margin-top: 5px;
}
.card-header {
  height: 60px;
  padding: 0px;
  padding-top: 23px;
  padding-left: 23px;
}

::-webkit-scrollbar-thumb {
  background-color: #7eb8ee;
}

.cdHead {
  height: 60vh !important;
  border: none;
}
.form-group {
  margin-bottom: 0.5rem;
}
.showContentRight {
  max-width: 50%;
  height: 466px;
  overflow-x: hidden;
  overflow-y: auto;
}
ul {
  list-style: none;
}
</style>
